# @author:Wei Junjie
# @time:2024/5/17 8:52
# @file demo01.py
# --*--coding: utf-8 --*--
"""
搜索引擎
"""
from flask import Flask,render_template,request,redirect

app = Flask(__name__)

app.config['SECRET_KEY'] = '192.168.0.105'
from PrivateSpider.JapaneseWebSearch import aqdyim
import base64

# CONST INFORMATION
PER_PAGE=10



# show detail content
@app.route("/<name>/page=<int:page>",methods=['GET','POST'])
def search_result(name,page=1):
    page=int(page)
    if request.method == 'GET':
        DB = aqdyim.Data_Sql()
        try:
            # picture = DB.search(name, 'picture')
            # title = DB.search(name,'title')
            # cili=DB.search(name,'bt')

            count_page=int(DB.page_count(name)[0])

            if count_page%PER_PAGE == 0:
                pge_number=int(count_page/PER_PAGE)
            else:
                pge_number=int(count_page/PER_PAGE)+1

            page_list=[i for i in range(1,pge_number+1)]

            picture = DB.search_data_page(name,'picture',page,PER_PAGE)
            title = DB.search_data_page(name,'title',page,PER_PAGE)
            cili=DB.search_data_page(name,'bt',page,PER_PAGE)

            if picture and title and cili:
                new_title = list(map(lambda x: ''.join(x), title))
                new_picture = list(map(lambda x: b''.join(x), picture))
                new_picture_list = list(map(lambda x: base64.b64encode(x).decode(), new_picture))
                new_cili = list(map(lambda x: ''.join(x), cili))
                new_data = []
                for index, item in enumerate(new_picture_list):
                    new_data.append({"title": new_title[index], "picture": item, 'cili': new_cili[index]})
                return render_template('test/index.html',data=new_data,
                                       name=name,pge_list=page_list,page_number=page,max_number=pge_number,
                                       page_prvious=page-1,page_next=page+1)
        except Exception as e:
            return render_template('test/404.html')
        else:
            return render_template('test/404.html')

# main page
@app.route('/',methods=['GET','POST'])
def index():
    if request.method == 'GET':
        return render_template('test/search.html')
    if request.method == 'POST':
        name=request.form.get('keywords','')
        data='/'+name+'/page=1'
        return redirect(data)

@app.route('/video',methods=['GET'])
def video():
    if request.method == 'GET':
        return render_template('test/video.html')


@app.before_request
def before_request():
    print("IP 是"+request.remote_addr)
    print('i am before request')
#
# @app.after_request
# def after_request(response):
#     print('i am after request')
#     return response

if __name__ == "__main__":
    app.run(host='192.168.0.105',port=5000,debug=True)